博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Ajax File Upload Response Handling
阅读量:6582 次
发布时间:2019-06-24

本文共 4920 字,大约阅读时间需要 16 分钟。

Ajax File Upload Response Handling

A while ago, I wrote an article on  - the method of uploading a file without refreshing the page using a hidden iframe. Since then people wanted to know how to get information about the uploaded file back into the javascript application. Consider this the second part of that article - this post will tell you how to get the information about the uploaded file in javascript.

A Sample Application

For example, say you are building a photo gallery. When a user uploads an image(using the above mentioned ajax method), you want to get its name and file size from the server side. First, lets create the Javascript uploading script(for explanation on this part, see the )...

The Code

And the server side(PHP in this case) script will look something like this...

false, "file_name" => $name, // Name of the file - JS should get this value "size" => $size // Size of the file - JS should get this as well. ));} else { // Upload failed for some reason. print json_encode(array( "success" => false, "failure" => $result, ));}

Here we are printing the data that should be given to JS directly into the iframe. Javascript can access this data by accessing the iframe's DOM. Lets add that part to the JS code...

function init() {	document.getElementById("file_upload_form").onsubmit=function() {		document.getElementById("file_upload_form").target = "upload_target";		document.getElementById("upload_target").onload = uploadDone; //This function should be called when the iframe has compleated loading			// That will happen when the file is completely uploaded and the server has returned the data we need.	}}function uploadDone() { //Function will be called when iframe is loaded	var ret = frames['upload_target'].document.getElementsByTagName("body")[0].innerHTML;	var data = eval("("+ret+")"); //Parse JSON // Read the below explanations before passing judgment on me		if(data.success) { //This part happens when the image gets uploaded.		document.getElementById("image_details").innerHTML = "
Size: " + data.size + " KB"; } else if(data.failure) { //Upload failed - show user the reason. alert("Upload Failed: " + data.failure); } }

Explanation

Lets see whats happening here - a play by play commentary...

document.getElementById("upload_target").onload = uploadDone;

Set an event handler that will be called when the iframe has compleated loading. That will happen when the file is completely uploaded and the server has returned the data we need. Now lets see the function uploadDone().

var ret = frames['upload_target'].document.getElementsByTagName("body")[0].innerHTML;var data = eval("("+ret+")");

These two lines are an eyesore. No - it goes beyond 'eyesore' - this is an abomination. If these lines causes you to gouge out your eyes and run for the hills, I can understand completely. I had to wash my hands after writing those lines. Twice.

var ret = frames['upload_target'].document.getElementsByTagName("body")[0].innerHTML;

This will get the data the server side script put in the iframe. This line cannot be avoided as far as I know. You can write it in different ways - but in the end, you will have to take the innerHTML or the nodeValue or something of the body element of the iframe. I used the smallest code in the sample. Even if you specify the Content type of the iframe page as text/plain, the browser will 'domify' it.

One other thing - in frames['upload_target'] the 'upload_target' is the name of the iframe - not the ID. Its a gotcha you need to be aware of.

var data = eval("("+ret+")");

Thankfully, this line can be avoided - you can use some other format(in this particular case the best format might be plain HTML) so that you don't have to parse a string that comes out of innerHTML. Or you can use CSV. Or plain text. Or JSON as we are doing right now - just parse it without using eval(). Reason I choose it? Smallest code - and easier to understand.

Now we have a working system. The files are uploaded and data reaches the client side. Everything works perfectly. Oh, how I wish I could say that. But nooo - the nightmare of every javascript developer rears its ugly head again...

Internet Explorer

Internet Explorer, also known as IE, also known as the Beast, again manages to mess things up. They don't support the onload event for iframe. So the code...

document.getElementById("upload_target").onload = uploadDone;

will not work. WILL. NOT. WORK. Thanks IE, thanks very much.

So, what do we do? We use a small hack. We put a script tag inside the iframe with a onload event that calls the uploadDone() of the top frame. So now the server side script looks like this...

Okay - now we have a IE-proof working system. Upload an image using the below demo application to see it in action.

If you have a better way of doing this, please, PLEASE let me know. I feel dirty doing it this way.

See it in Action

 

转载地址:http://qjsno.baihongyu.com/

你可能感兴趣的文章
中国人社部:2018年15个省(区、市)调整最低工资标准
查看>>
手把手教你通过Thrift 访问ApsaraDB for HBase
查看>>
MacOS安装MySQL 报错
查看>>
Java知识点总结(反射-反射操作泛型)
查看>>
Vue+webpack+Element 兼容问题总结
查看>>
《软技能》读书笔记(下)
查看>>
textarea文域高度自适应
查看>>
go语言renderer包代码分析
查看>>
【Scala谜题】成员声明的位置
查看>>
git最最最最...常用命令
查看>>
复杂recyclerView封装库
查看>>
见微知著 —— Redis 字符串内部结构源码分析
查看>>
Command './js-ant' failed to execute
查看>>
阿里云NFS NAS数据保护实战
查看>>
Spring cloud配置客户端
查看>>
产品研发项目管理软件哪个好?
查看>>
【阿里云北京峰会】一图看懂机器学习PAI如何帮助企业应用智能化升级
查看>>
Android API中文文档(111) —— MailTo
查看>>
Linux 中如何卸载已安装的软件
查看>>
thinkphp 3.2 增加每页显示条数
查看>>